package org.ediba.siri.core.image.data;

import static org.hibernate.criterion.Example.create;

import java.util.Collection;
import java.util.Map;
import org.ediba.siri.core.Filter;
import org.ediba.siri.core.common.data.HibernateDomainDao;
import org.ediba.siri.core.image.domain.ImageAlbum;
import org.hibernate.criterion.Conjunction;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;

public class HibernateImageAlbumDao extends HibernateDomainDao<ImageAlbum, Integer> implements ImageAlbumDao {

	public HibernateImageAlbumDao() {super(ImageAlbum.class);}

	@Override
	protected DetachedCriteria buildCriteria(ImageAlbum example) {
		DetachedCriteria detachedCriteria = this.buildCriteria();
		detachedCriteria.add(create(example));
		detachedCriteria.createCriteria(Filter.USER.getProperty()).add(create(example.getUser()));
		return detachedCriteria;
	}
		
	@Override
	protected DetachedCriteria buildCriteria(Collection<Map<Filter, Object>> filters) {
		DetachedCriteria detachedCriteria = this.buildCriteria();
		
		Disjunction or = Restrictions.disjunction();
		Conjunction and;
		
		for (Map<Filter, Object> map : filters) {
			and = Restrictions.conjunction();
			for (Map.Entry<Filter,Object> entry: map.entrySet())
				switch (entry.getKey()) {
					case ID: and.add(Restrictions.idEq(entry.getValue()));
					break;
					case NAME: and.add(Restrictions.ilike(Filter.NAME.getProperty(), (String)entry.getValue(), MatchMode.ANYWHERE));
					break;
					case USER: and.add(Restrictions.eq(Filter.USER.getPropertyId(),entry.getValue()));
					break;
				}
			or.add(and);
		}
		detachedCriteria.add(or);
		
		return detachedCriteria;
	}
	
}
